/**
 *  @constant HTTP_REQUEST_URL 域名 
 * */
let HTTP_REQUEST_URL = 'https://2398.srkjapp.com'

/** 
 * @Function  跳转到登录页
 */
function toLogin() {
	uni.navigateTo({
		url: '/pages/login/index'
	})
}
/**
 * 发起请求
 * @param url 请求地址接口
 * @param method 请求方式
 * @param data 传递参数
 */
function baseRequest(url, method, data, {
	noAuth = false,
}) {
	let token = uni.getStorageSync('token')
	let Url = HTTP_REQUEST_URL
	let header = {
		"XX-Device-Type": 'wxapp',
		"XX-Token": uni.getStorageSync('token') || 'token'
	};

	// 请求前校验token
	if (!noAuth) {
		//登录过期自动登录
		if (!token && token == '') {
			toLogin();
			return uni.showToast({
				title: '未登录',
				duration: 2000
			});
		}
	}

	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + url, // 域名+接口
			method: method || 'GET', // 默认get
			header: header, // 默认携带 header
			data: data || {}, // 携带数据或者空
			success: (res) => {
				// console.log('成功', res.data);
				// 判断返回结果 进行处理
				if (res.data.code == 1) {
					reslove(res.data, res);
				} else if (res.data.code == 0) {
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 2000
					});
				} else {
					reject(res.data.msg || "系统错误");
				}
			},
			fail: (msg) => {
				// console.log('失败', res.data);
				let data = {
					mag: "请求失败",
					status: 1 //1没网
				}
				reject(data || "请求失败");
			}
		})
	});
}
const request = {};
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});
export default request;